package com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.handler;

import com.caiyi.financial.nirvana.sms.gateway.DefaultGateWay;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.GatewayControlHandler;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.message.CMPP3Message;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.message.body.CMPP3ActiveTest;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.message.body.CMPP3Connection;
import com.caiyi.financial.nirvana.sms.util.Constant;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CMPP3ControlHandler extends GatewayControlHandler {

    private static final Logger logger = LoggerFactory.getLogger(CMPP3ControlHandler.class);

    public CMPP3ControlHandler(DefaultGateWay gateWayInfo) {
        this.gateWayInfo = gateWayInfo;
    }

    //登录
    @Override
    public void doLogin(ChannelHandlerContext ctx) {
        logger.info(gateWayInfo.info.getName() + " 正在登录。。。");
        CMPP3Message loginMessage = new CMPP3Message();
        CMPP3Connection cmppConnection = new CMPP3Connection(gateWayInfo.info.getAccount(), gateWayInfo.info.getPassword());
        loginMessage.setCommandID(CMPP3Message.CMPP_CONNECT);
        loginMessage.setSequenceId(Constant.seqNo.incrementAndGet());
        loginMessage.setBody(cmppConnection);
        ctx.writeAndFlush(loginMessage);
    }

    //心跳
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            //读空闲事件，触发重连，关闭当前连接；否则发送心跳包给服务器
            if (event.state().equals(IdleState.READER_IDLE)) {
                logger.info(gateWayInfo.info.getName() + " 触发读空闲事件，连接关闭！");
                ctx.close();
            } else {
                int sequenceId = Constant.seqNo.incrementAndGet();
                logger.info(gateWayInfo.info.getName() + " 触发心跳测试。sequenceId : {}", sequenceId);
                CMPP3Message message = new CMPP3Message();
                message.setCommandID(CMPP3Message.CMPP_ACTIVE_TEST);
                message.setSequenceId(sequenceId);
                CMPP3ActiveTest activeTest = new CMPP3ActiveTest();
                message.setBody(activeTest);
                ctx.writeAndFlush(message);
            }
        }
    }

}
